//
//  EventsViewController.swift
//  event列表显示：包括删除event、查看详情、前后切换日期、下拉刷新、match和reee、获取slots列表等功能
//
//  Created by JennyShi on 2018/4/10.
//  Copyright © 2018年 Apple Inc. All rights reserved.
//

import UIKit
import os.log
import Hyphenate
import MobileCoreServices
import MBProgressHUD
import Alamofire
import PGDatePicker

class EventsViewController: UIViewController, EventDetailDelegate, UITableViewDelegate, UITableViewDataSource {
    func didSaved(cuEvent0: CuEvent?, ownerGo0: String) {
        
        
    }
    


    //显示eventArr用
    var eventsTableView : UITableView = UITableView()
    
    //传进来的参数
    var statusPara = StatusPara(hasFriend:false,friendOwner:"",loginOwner:"",sourceViewControllerType:1,dateTitle:"",date:Date(),calendarTypeNumber:0,matchOrFree:0,languageNow:"")
    var dateTitle : String?
    var loginOwner : String?
    var calendarTypeNumber = 0
    var hasFriend = false
    var friendOwner : String?
    var matchOrFree = 0
  
    var isGroup = false;
    //events显示数组
    var eventsArr = [CuEvent]()
    //slots显示数组
    var slotsArrMatch = [Slot]()
    var slotsArrFree = [Slot]()
    //选中的slot
    var selectedSlotMatch = Slot(startTime: "",endTime: "")
    var selectedSlotFree = Slot(startTime: "",endTime: "")

    //屏幕宽度
    var screenX: CGFloat = 0.0
    var screenY: CGFloat = 0.0
    var screenWidth : CGFloat = 0.0
    var screenHeight : CGFloat = 0.0

    var pickerDateString = ""
    
    var dateFormatter = DateFormatter()
    var fromDate = Date()
    var toDate = Date()

    //两行标题
    var titleView = UIView()
    var btnLeft = UIButton()
    var btnRight = UIButton()
    var btnSeleteDate = UIButton()
    var btnMatch = UIButton()
    var btnFree = UIButton()
    
    var showDateStr = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //获得手机正在使用的语言
        statusPara?.languageNow = EnStatic.languegeUsing()
        
        // 设置传进来的参数
        if statusPara == statusPara {
            hasFriend = (statusPara?.hasFriend)!
            friendOwner = statusPara?.friendOwner
            loginOwner = statusPara?.loginOwner
            dateTitle = statusPara?.dateTitle
            calendarTypeNumber = (statusPara?.calendarTypeNumber)!
            matchOrFree = (statusPara?.matchOrFree)!
        } else {
            let dformatter = DateFormatter()
            dformatter.dateFormat = "yyyy-MM-dd"
            dateTitle = dformatter.string(from: Date())
            loginOwner = EMClient.shared().currentUsername
        }

        //获取login的userID
        if loginOwner == nil || (loginOwner?.isEmpty)! {
            loginOwner = EMClient.shared().currentUsername
        }
        
        
        if dateTitle!.count > 0 {
            
           showDateStr =  getWeekDay(dayStr: dateTitle!)
        }

        //获取屏幕大小
        let viewBounds:CGRect = UIScreen.main.bounds
        
        screenX = viewBounds.origin.x
        screenY = viewBounds.origin.y
        screenWidth = viewBounds.width
        screenHeight = viewBounds.height
        
        eventsTableView.frame = CGRect(x: screenX, y: screenY , width: screenWidth, height: screenHeight - 64)
        
        eventsTableView.rowHeight = UITableViewAutomaticDimension
        eventsTableView.estimatedRowHeight = 300
        eventsTableView.tableFooterView = UIView()
        
        eventsTableView.register(UINib.init(nibName: "EventListTableCell", bundle: nil), forCellReuseIdentifier: "EventListTableCell")
        //去掉背景线条显示
        self.eventsTableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
//        self.eventsTableView.separatorColor = UIColor.clear
        pickerDateString = dateTitle!
        titleView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: (isGroup == true ? 0 :(hasFriend == true ? 80 : 40)))
        
         if(!isGroup){
        btnLeft.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        btnLeft.setTitle("<", for: UIControlState.normal)
        btnLeft.addTarget(self, action: #selector(dateSetLeft), for: UIControlEvents.touchUpInside)
        btnLeft.backgroundColor = KermitGreenTwoColor
        btnRight.frame = CGRect(x: screenWidth - 40, y: 0, width: 40, height: 40)
        btnRight.setTitle(">", for: UIControlState.normal)
        btnRight.addTarget(self, action: #selector(dateSetRight), for: UIControlEvents.touchUpInside)
        btnRight.backgroundColor = KermitGreenTwoColor
       
        btnSeleteDate.frame = CGRect(x: 40, y: 0, width: screenWidth-80, height: 40)
        btnSeleteDate.setTitle(showDateStr, for: UIControlState.normal)
        btnSeleteDate.addTarget(self, action: #selector(dateSet), for: UIControlEvents.touchUpInside)
        btnSeleteDate.backgroundColor = KermitGreenTwoColor
            
            titleView.addSubview(btnLeft)
            titleView.addSubview(btnRight)
            titleView.addSubview(btnSeleteDate)
        }
        if hasFriend && !isGroup{
            btnMatch.frame = CGRect(x: screenWidth/2+5, y: 42, width:screenWidth/2-10, height: 35)
            btnMatch.setTitle(EnStatic.getWord(keyWord: "Match"), for: UIControlState.normal)
            btnMatch.addTarget(self, action: #selector(getMatch), for: UIControlEvents.touchUpInside)
            btnMatch.backgroundColor = WhiteColor
            btnMatch.layer.borderWidth = 1.0
            btnMatch.setTitleColor(AlmostBlackColor, for: UIControlState.normal)
            btnMatch.layer.borderColor = UIColor.lightGray.cgColor
            btnMatch.layer.cornerRadius = 10.0
            btnFree.frame = CGRect(x: 5, y: 42, width: screenWidth/2-10, height: 35)
            btnFree.setTitle(EnStatic.getWord(keyWord: "Free"), for: UIControlState.normal)
            btnFree.addTarget(self, action: #selector(getFree), for: UIControlEvents.touchUpInside)
            btnFree.backgroundColor = WhiteColor
            btnFree.setTitleColor(AlmostBlackColor, for: UIControlState.normal)
            btnFree.layer.borderWidth = 1.0
            btnFree.layer.borderColor = UIColor.lightGray.cgColor
            btnFree.layer.cornerRadius = 10.0
            
            titleView.addSubview(btnMatch)
            titleView.addSubview(btnFree)
        }
        eventsTableView.tableHeaderView = titleView

        getEventsFromBackend(calendarTypeNumber: calendarTypeNumber,dateString: pickerDateString)

        self.view.addSubview(eventsTableView)
        
        eventsTableView.delegate = self
        eventsTableView.dataSource = self
        
        eventsTableView.refreshControl = UIRefreshControl()
        eventsTableView.refreshControl?.attributedTitle = NSAttributedString(string: EnStatic.getWord(keyWord: "Pull down to refresh"))
        eventsTableView.refreshControl?.addTarget(self, action: #selector(pullDownRefreshing), for: UIControlEvents.valueChanged)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //下拉刷新
    @objc func pullDownRefreshing(){

        //向后端重新申请数据

        getEventsFromBackend(calendarTypeNumber: calendarTypeNumber, dateString: pickerDateString)
        eventsTableView.refreshControl?.endRefreshing()
        eventsTableView.reloadData()
        
    }
    
    func getWeekDay(dayStr: String) -> String {
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        
        let date = dateFormatter.date(from: dayStr)
        
        dateFormatter.dateFormat = "yyyy-MM-dd EEEE"
        
        let dateStr = dateFormatter.string(from: date!)
        
//        var weekStr = dateStr.split(separator: " ")[1]
        
        return String(dateStr)
    }
    
    
    private func selectDate() {
        let datePickerManager = PGDatePickManager()
        let datePicker = datePickerManager.datePicker!
        datePicker.delegate = self
        datePicker.isHiddenMiddleText = false;
//        datePicker.datePickerType = .type2;
        datePicker.datePickerMode = .date
        datePicker.tag = 1000
//        datePicker.minimumDate = Date()
        self.present(datePickerManager, animated: false, completion: nil)
    }
    
    //MARK: 选择日期
    @objc func dateSet() {
        
        let datePickerManager = PGDatePickManager()
        let datePicker = datePickerManager.datePicker!
        datePicker.delegate = self
        datePicker.isHiddenMiddleText = false;
//        datePicker.datePickerType = .type2;
        datePicker.datePickerMode = .date
        datePicker.tag = 1000
        datePicker.minimumDate = Date()
        self.present(datePickerManager, animated: false, completion: nil)
    }
    
    @objc func dateSetLeft() {
        pickerDateString = EventsViewController.getLastNextDay(pickerDateString,lastNext: true)
        
        showDateStr = getWeekDay(dayStr: pickerDateString)
        
        btnSeleteDate.setTitle(showDateStr, for: UIControlState.normal)
        getEventsFromBackend(calendarTypeNumber: calendarTypeNumber,dateString: pickerDateString)
        eventsTableView.reloadData()
    }
    
    @objc func dateSetRight() {
        pickerDateString = EventsViewController.getLastNextDay(pickerDateString,lastNext: false)
        showDateStr = getWeekDay(dayStr: pickerDateString)
        btnSeleteDate.setTitle(showDateStr, for: UIControlState.normal)
        getEventsFromBackend(calendarTypeNumber: calendarTypeNumber,dateString: pickerDateString)
        eventsTableView.reloadData()
    }
    
    class func getLastNextDay(_ nowDay: String, lastNext: Bool) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        
        let date = dateFormatter.date(from: nowDay)
        let tmpTimeInterval = lastNext ? (-1) * (24 * 60 * 60) : 24 * 60 * 60    // 往前减去一天的秒数，昨天
        let lastTime: TimeInterval = TimeInterval(tmpTimeInterval)
        
        let lastDate = date?.addingTimeInterval(lastTime)
        let lastDay = dateFormatter.string(from: lastDate!)
        return lastDay
    }

    @objc func dateSelectOkButtonTapped() {
        eventsTableView.isHidden = false
        getEventsFromBackend(calendarTypeNumber: calendarTypeNumber,dateString: pickerDateString)
        eventsTableView.reloadData()
    }
    
    //日期选择器响应方法
    @objc func dateChanged(datePicker : UIDatePicker){
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        pickerDateString = formatter.string(from: datePicker.date)
        btnSeleteDate.setTitle(pickerDateString, for: UIControlState.normal)
        getEventsFromBackend(calendarTypeNumber: calendarTypeNumber,dateString: pickerDateString)
        eventsTableView.reloadData()
    }
    
    //myPicker的ok按钮
    @objc func okButtonMyPickerTapped() {
        
        // FIXME:
        //login的owner的userid
        let loginOwner = EMClient.shared().currentUsername
        let date = Date()
        let dformatter = DateFormatter()
        dformatter.dateFormat = "yyyy-MM-dd"
        let dateTitle = dformatter.string(from: date)
        //必须全传进去，因为进去后先执行两个segue，后执行viewDidLoad，来不及合成dateTitle和取owner
//        let statusPara = StatusPara(hasFriend:(!friendOwner.isEmpty),friendOwner:friendOwner,loginOwner:loginOwner!,sourceViewControllerType:1,dateTitle:dateTitle,date:date,calendarTypeNumber:0,matchOrFree:0,languageNow:languageNow)
        
        statusPara?.dateTitle = pickerDateString
        statusPara?.sourceViewControllerType = EnStatic.fromMatchFreeWithDateAndSlot
        statusPara?.matchOrFree = matchOrFree
        
        weak var weakSelf = self
        let storyboard = UIStoryboard.init(name: "AddNewEvent", bundle: nil)
        let vc = storyboard.instantiateInitialViewController() as? AddNewEventTableVC
        vc?.statusPara = statusPara
                if matchOrFree == 0 {
                    vc?.startTimeStr = (selectedSlotMatch?.estartTime)!
                    vc?.endTimeStr = (selectedSlotMatch?.eendTime)!
                } else {
                    vc?.startTimeStr = (selectedSlotFree?.estartTime)!
                    vc?.endTimeStr = (selectedSlotFree?.eendTime)!
                }
        weakSelf?.navigationController?.pushViewController(vc!, animated: true)
        
    }
    
    // FIXME:选择free match 时间
    
    func selectDatePicker() {
        
        //初始化UIPickerView
        var pickerView = UIPickerView()
        pickerView.dataSource = self
        pickerView.delegate = self
        //设置选择框的默认值
        pickerView.selectRow(0,inComponent:0,animated:true)
        //把UIPickerView放到alert里面（也可以用datePick）
        let alertController:UIAlertController=UIAlertController(title: "\n\n\n\n\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
        alertController.addAction(UIAlertAction(title: "Select".localized(), style: UIAlertActionStyle.default){
            (alertAction)->Void in
            print("date select:" + String(pickerView.selectedRow(inComponent: 0)+1))
            self.okButtonMyPickerTapped()
        })
        alertController.addAction(UIAlertAction(title: "Cancel".localized(), style: UIAlertActionStyle.cancel,handler:nil))
        pickerView.frame = CGRect(x: 10, y: 0, width: screenWidth - 20, height: 250);
        alertController.view.addSubview(pickerView)
        self.present(alertController, animated: true, completion: nil)
    }
    
    @objc func getMatch() {
        
        getMatchSlotsFromBackend(dateString: pickerDateString)
    }
    
    @objc func getFree() {
        
        getFreeSlotsFromBackend(dateString: pickerDateString)
    }
 
    //match取后端的slots数据
    private func getMatchSlotsFromBackend(dateString : String) {
        
        var urlString : String = ""
        
        urlString = "slots?slotType=match&user2=" + loginOwner! + "&user1=" + friendOwner! + "&date=" + dateString

        let cuHTTP = CUHTTP.instance()
        
        cuHTTP.makeGetData(url: urlString, success: {response in
            //将response.result.value解析为字典并写入数组
            if let value = response?.result.value {
                let data = value.data(using: String.Encoding.utf8)! as NSData
                let json = try? JSONSerialization.jsonObject(with: data as Data,
                                                             options:.allowFragments) as! [String: [Any]]
              
                //allSlots为所有的slots，是个数组，数组元素为字典
                let allSlots = json!["slots"]
                var startTime = ""
                var endTime = ""
                self.slotsArrMatch.removeAll()
                //逐条写入显示数组slotsArrMatch或slotsArrFree
                for loopSlot in allSlots! {
                    let loopE = loopSlot as! [String]
                    //不加减一分钟self.dateFormatter.string(from: self.fromDate)报错
                    startTime = loopE[0].compare("24:00").rawValue == 0 ? "23:59" : (loopE[0].compare("00:00").rawValue == 0 ? "00:01" : loopE[0])
                    endTime = loopE[1].compare("24:00").rawValue == 0 ? "23:59" : (loopE[1].compare("00:00").rawValue == 0 ? "00:01" : loopE[1])
                    self.dateFormatter.dateFormat = "HH:mm"
                    self.fromDate = self.dateFormatter.date(from: startTime)!
                    self.toDate = self.dateFormatter.date(from: endTime)!
                    if EnStatic.languegeUsing().compare("en").rawValue == 0 {
                        self.dateFormatter.dateFormat = "hh:mm"
                    } else {
                        self.dateFormatter.dateFormat = "HH:mm"
                    }
                    startTime = self.dateFormatter.string(from: self.fromDate)
                    endTime = self.dateFormatter.string(from: self.toDate)
                    if EnStatic.languegeUsing().compare("en").rawValue == 0 {
                        startTime = EventsViewController.HHmmTohhmma(dateStr: startTime)
                        endTime = EventsViewController.HHmmTohhmma(dateStr: endTime)
                    }
                    guard let tmpSlot = Slot(startTime : startTime, endTime : endTime) else {
                        fatalError("Unable to instantiate CuEvent1")
                    }
                    self.slotsArrMatch.append(tmpSlot)
                }
                if self.slotsArrMatch.count > 0 {
                    self.selectedSlotMatch = self.slotsArrMatch[0]
                }
                
                self.showMatch();
            }
        }, failure:{ response in
            //            print(response ?? " ")
            self.myAlert(message000: "get data failed")
        }
        )
    }
    
    //free取后端的slots数据
    private func getFreeSlotsFromBackend(dateString : String)
    {
        
        var urlString : String = ""
        
        urlString = "slots?slotType=free&user2=" + loginOwner! + "&user1=" + friendOwner! + "&date=" + dateString
        let cuHTTP = CUHTTP.instance()
        
        cuHTTP.makeGetData(url: urlString, success: {response in
            //将response.result.value解析为字典并写入数组
            if let value = response?.result.value {
                let data = value.data(using: String.Encoding.utf8)! as NSData
                let json = try? JSONSerialization.jsonObject(with: data as Data,
                                                             options:.allowFragments) as! [String: [Any]]

                //allSlots为所有的slots，是个数组，数组元素为字典
                let allSlots = json!["slots"]
                var startTime = ""
                var endTime = ""
                self.slotsArrFree.removeAll()
                //逐条写入显示数组slotsArrMatch或slotsArrFree
                for loopSlot in allSlots! {
                    let loopE = loopSlot as! [String]
                    //不加减一分钟self.dateFormatter.string(from: self.fromDate)报错
                    startTime = loopE[0].compare("24:00").rawValue == 0 ? "23:59" : (loopE[0].compare("00:00").rawValue == 0 ? "00:01" : loopE[0])
                    endTime = loopE[1].compare("24:00").rawValue == 0 ? "23:59" : (loopE[1].compare("00:00").rawValue == 0 ? "00:01" : loopE[1])
                    self.dateFormatter.dateFormat = "HH:mm"
                    self.fromDate = self.dateFormatter.date(from: startTime)!
                    self.toDate = self.dateFormatter.date(from: endTime)!
                    if EnStatic.languegeUsing().compare("en").rawValue == 0 {
                        self.dateFormatter.dateFormat = "hh:mm a"
                    } else {
                        self.dateFormatter.dateFormat = "HH:mm"
                    }
                    startTime = self.dateFormatter.string(from: self.fromDate)
                    endTime = self.dateFormatter.string(from: self.toDate)
                    if EnStatic.languegeUsing().compare("en").rawValue == 0 {
                        startTime = EventsViewController.HHmmTohhmma(dateStr: startTime)
                        endTime = EventsViewController.HHmmTohhmma(dateStr: endTime)
                    }
                    guard let tmpSlot = Slot(startTime : startTime, endTime : endTime) else {
                        fatalError("Unable to instantiate CuEvent1")
                    }
                    self.slotsArrFree.append(tmpSlot)
                }
                if self.slotsArrFree.count > 0 {
                    self.selectedSlotFree = self.slotsArrFree[0]
                }
                self.showFree();
            }
        }, failure:{ response in
            self.myAlert(message000: "get data failed")
        }
        )
    }
    
    
    @objc func showMatch() {
        
        if slotsArrMatch.count <= 0 {
            eventsTableView.isHidden = false
            myAlert(message000: "No match time available".localized())
            return
        }
 
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let date = dateFormatter.date(from: pickerDateString + " 23:59:59")
        if date! < Date() {
            eventsTableView.isHidden = false
            return
        }

        selectedSlotMatch = slotsArrMatch[0]
        
        //取得selectedSlotMatch
        matchOrFree = 0
        
        selectDatePicker()

    }
    
    @objc func showFree() {
        
        
        if slotsArrFree.count <= 0 {
            eventsTableView.isHidden = false
            myAlert(message000: "No free time available".localized())
            return
        }
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let date = dateFormatter.date(from: pickerDateString + " 23:59:59")
        if date! < Date() {
            eventsTableView.isHidden = false
            return
        }
        
        selectedSlotFree = slotsArrFree[0]
        
        //取得selectedSlotMatch

        matchOrFree = 1
        
        selectDatePicker()

    }
    
    //删除事件
    @objc func deleteEvent() {
        
        eventsTableView.setEditing(!eventsTableView.isEditing, animated: true)
        
        if eventsTableView.isEditing {
            btnMatch.setTitle(EnStatic.getWord(keyWord: "Done"), for: UIControlState.normal)
        } else {
            btnMatch.setTitle(EnStatic.getWord(keyWord: "Delete"), for: UIControlState.normal)
        }
        
    }
    
    func postDeleteEvent(event : CuEvent) {
        //在此需要将event转换为JSONObject并写入parameters
        let value = event
        

        let id = value.eid
        
        let cuHTTP = CUHTTP.instance()
        let urlstr = "event"
        var parameters: [String: Any]
        
        parameters = [
            "eventId" : id,
            "delete" : "true"
        ]
        
        cuHTTP.makePostData(url: urlstr, parameters: parameters,
                            success: {response in
                                //成功时，返回200
        } ,
                            failure: {response in
                                self.myAlert(message000: "delete failed")
        }
        )
    }

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        
        //只有自己创建的，且自己浏览时才能删除
        if !hasFriend {
            let deleteEvent = eventsArr[indexPath.row]
            if deleteEvent.eowner.compare(loginOwner!).rawValue == 0 {
                return true
            }
        }

        return false
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        return UITableViewCellEditingStyle.delete
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            postDeleteEvent(event: eventsArr[indexPath.row])
            eventsArr.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
            tableView.reloadData()
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return eventsArr.count
    }
    // MARK:FIXEME:
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cellid = "EventListTableCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: cellid)
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: cellid)
        }
        
        let event = eventsArr[indexPath.row] as CuEvent
        
        let curCell = cell as? EventListTableCell
        
        
        curCell?.titleLabel.text = event.eeventTitle
        //不在列表当中显示详情
//        if(hasFriend){
//            curCell?.contentLabel.height(height: 0);
//        }else{
//
//            curCell?.contentLabel.text = event.edescription
//        }
        // + event.edate + " " +
        
        var time_srt = ""
        if(isGroup){
            time_srt = event.edate + "  "
        }
        if event.estartTime.count > 0 && event.eendTime.count > 0
        {
           time_srt +=
            CUTimeFormat.get12Time(time: event.estartTime) + " - " +
            CUTimeFormat.get12Time(time: event.eendTime)
        }
        
        curCell?.timeLabel.text = time_srt
        if(time_srt != ""){
            curCell?.timeLabel.height(height: 0)
        }
        
        

        curCell?.timeStatusLabel.text = " " + event.eeventType + " "
        if(!hasFriend){
            if(event.eloginOwnerGo == "going")
            {
                curCell?.statusView.backgroundColor =  UIColor.pg_color(withHexString: "#2873DF")
            }
            else if(event.eloginOwnerGo == "unread")
            {
                curCell?.statusView.backgroundColor =  UIColor.lightGray
            }
            else if(event.eloginOwnerGo == "notgoing")
            {
                curCell?.statusView.backgroundColor =  UIColor.pg_color(withHexString: "#FF1D23")
            }
        }
        return curCell!
    }


    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if !hasFriend || isGroup {
           
            let selectedEvent = eventsArr[(indexPath.row)]
            weak var weakSelf = self
            let storyboard = UIStoryboard.init(name: "EventDetailVC", bundle: nil)
            let vc = storyboard.instantiateInitialViewController() as! EventDetailVC
            vc.eid = selectedEvent.eid
            weakSelf?.navigationController?.pushViewController(vc, animated: true)
        }
        
  

    }
    
    // MARK: - Navigation
    
    //cell选中后用segue跳转时才会执行这里。尽量不要用segue方法
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        super.prepare(for: segue, sender: sender)
        switch(segue.identifier ?? "") {
        case "eventListToDetail":
            guard let eventListDetailViewController = segue.destination as? EventDetail else {
                fatalError("Unexpected destination: \(segue.destination)")
            }
            let indexPath = eventsTableView.indexPathForSelectedRow
            let selectedEvent = eventsArr[(indexPath?.row)!]
            eventListDetailViewController.cuEvent = selectedEvent
            if selectedEvent.eowner.compare(loginOwner!).rawValue == 0 {
                eventListDetailViewController.sourceViewControllerType = EnStatic.fromEventListToSeeFriendsReply
//                eventListDetailViewController.myClosure = myClosureMethod
            } else {
                if hasFriend {
                    eventListDetailViewController.sourceViewControllerType = EnStatic.fromEventListToSeeFriendsReply
                } else {
                    eventListDetailViewController.sourceViewControllerType = EnStatic.fromEventListToReplyFriend
                }
            }
            os_log("Go to detail", log: OSLog.default, type: .debug)
        default:
            fatalError("Unexpected Segue Identifier; \(String(describing: segue.identifier))")
        }
        
    }
    
    //MARK: Private Methods
    
    //用data方式取后端event数据，分为loginOwner自己的和friendOwner的两种，每种又分别分为public和personal两种
    private func getEventsFromBackend(calendarTypeNumber : Int, dateString : String) {
 
        if(isGroup && calendarTypeNumber == 1){
            return
        }
        //根据loginOwner和日期合成urlstr
        var urlString : String = ""
        
        if  hasFriend {
            switch calendarTypeNumber {
            case 0:     //public
                urlString = "event?date=" + dateString + "&guest=" + friendOwner! + "&calendarType=public&status=going"
            case 1:     //personal
                urlString = "event?date=" + dateString + "&guest=" + friendOwner! + "&calendarType=private&status=going"
            default:
                urlString = "event?date=" + dateString + "&guest=" + friendOwner! + "&calendarType=public&status=going"
            }
        } else {
            switch calendarTypeNumber {
            case 0:     //public
                urlString = "event?date=" + dateString + "&guest=" + loginOwner! + "&calendarType=public"
            case 1:     //personal
                urlString = "event?date=" + dateString + "&guest=" + loginOwner! + "&calendarType=private"
            default:
                urlString = "event?date=" + dateString + "&guest=" + loginOwner! + "&calendarType=public"
            }
        }
        
        if(isGroup){
            urlString = "event?&groupId=" + friendOwner!
        }
        let cuHTTP = CUHTTP.instance()
        
        var isGroupScrollIndex = 1;
        cuHTTP.makeGetData(url: urlString, success: {response in
                //将response.result.value解析为字典并写入数组eventsArr
            
                if let value = response?.result.value {
                    let data = value.data(using: String.Encoding.utf8)! as NSData
                    let json = try? JSONSerialization.jsonObject(with: data as Data,
                            options:.allowFragments) as! [String: Any]
                    //allEvents为所有的events，是个数组，数组元素为字典
                    let allEvents = json!["events"] as! [Any]
//                    print(allEvents)
                    self.eventsArr.removeAll()
                    //逐条写入显示数组eventsArr
                    
                    
                    
                    let dateFormatter = DateFormatter.init()
                    dateFormatter.dateFormat = "yyyy-MM-dd"
                    for loopEvent in allEvents {
                        let loopE = loopEvent as! [String: Any]
                        let id = loopE["_id"] as! String
                        let owner = loopE["owner"] as! String
                        let calendarType000 = loopE["calendarType"] as! String
                        let eventType000 = loopE["eventType"] as! String
                        let eventTitle = loopE["eventTitle"] as! String
                        let description = loopE["description"] as! String
                        let date = loopE["date"] as! String
                            let event_date = dateFormatter.date(from: date)
                            if(event_date! < Date()){
                                isGroupScrollIndex += 1
                            }
                        
                        let startTime = loopE["startTime"] as! String
                        let endTime = loopE["endTime"] as! String
//                        let timeSensibility000 = loopE["timeSensibility"] as! String
//                        print(timeSensibility000)

                        
                        let gStatusArray = loopE["guestStatus"] as! [Any]
                        var gName = ""
                        var gStatus = ""
                        var loginOwnerGo = "unknown"
                        var friendOwnerGo = "unknown"
                        for gJson in gStatusArray {
                            var tmp = gJson as! [String:String]
                            gName = tmp["guest"] as! String!
                            gStatus = tmp["status"] as! String!
                            //根据loginOwner是否去来分颜色，不管是自己创建的还是别人创建后邀请的
                            if gName.compare(self.loginOwner! as String).rawValue == 0 {
                                loginOwnerGo = gStatus
                            }
                            if self.hasFriend {
                                if gName.compare(self.friendOwner! as String).rawValue == 0 {
                                    friendOwnerGo = gStatus
                                }
                            }
                        }
                        let calendarType = EnStatic.getWord(keyWord: calendarType000)
                        let eventType = EnStatic.getWord(keyWord: eventType000)

                        guard let tmpEvent = CuEvent(id : id , owner : owner , calendarType : calendarType , eventType : eventType , eventTitle : eventTitle, description : description, date : date, startTime : startTime, endTime : endTime, timeSensibility : "", guestStatus : "" , friendGo : friendOwnerGo, photo : nil, loginOwnerGo : loginOwnerGo) else {
                            fatalError("Unable to instantiate CuEvent1")
                        }
                        self.eventsArr.append(tmpEvent)
                    }
                }
                //因为是异步申请数据，所以要reload
                self.eventsTableView.reloadData()
            if(self.isGroup){
                let index = IndexPath(row: isGroupScrollIndex, section: 0)
//                if(self.eventsArr.count == index.row){
//                    self.eventsTableView.scrollToRow(at: IndexPath(row: isGroupScrollIndex , section: 0), at: .none, animated: true)
//                }
                if(self.eventsArr.count > index.row){
                self.eventsTableView.scrollToRow(at: index, at: .none, animated: true)
                }
                
            }
            },
            failure:{ response in
                self.myAlert(message000: "get data failed")
            }
        )

    }

    

    
    func myAlert(message000 : String) {
        let alertController = UIAlertController(title: "",message: EnStatic.getWord(keyWord: message000), preferredStyle: .alert)
        let okAction = UIAlertAction(title: EnStatic.getWord(keyWord: "OK"), style: .default, handler: {
            action in
            print("ok clicked")
        })
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }

    //24小时制改为12小时制
    //12:36am 是午夜12点36分
    //12:36pm 是下午12点36分
    open class func HHmmTohhmma(dateStr: String)->String {
        
//        if dateStr.isEmpty {
//            return ""
//        }
//        if dateStr.count >= 8 {
//            return dateStr
//        }
//
//        var hh = dateStr.subString(start: 0,length: 2)
//        let mm = dateStr.subString(start: 3,length: 2)
//        var aa = "AM"
//
//        let oldinthh = EventDetail.StringToInt(str: hh)
//        var inthh = oldinthh
//        if oldinthh == 0 {
//            inthh = 12
//        }
//        if oldinthh > 11 {
//            aa = "PM"
//        }
//        if oldinthh > 12 {
//            inthh = oldinthh - 12
//        }
//        hh = String(inthh)
//        if inthh < 10 {
//            hh = "0" + hh
//        }
//
//        let tmpTimeString: String = hh + ":" + mm + " " + aa
        
        return dateStr
        
    }
    
    //12小时制改为24小时制
    open class func hhmmaToHHmm(dateStr: String)->String {
        if dateStr.isEmpty {
            return ""
        }
        if dateStr.count <= 5  {
            return dateStr
        }
        
        var hh = dateStr.subString(start: 0,length: 2)
        let mm = dateStr.subString(start: 3,length: 2)
        let aa = dateStr.subString(start: 6,length: 2)

        var inthh = EventDetail.StringToInt(str: hh)
        if aa.compare("PM").rawValue == 0 || aa.compare("pm").rawValue == 0 {
            inthh = inthh + 12
            if inthh >= 24 {
                inthh = inthh - 12
            }
        } else {
            if inthh == 12 {
                inthh = 0
            }
        }
        hh = String(inthh)
        if inthh < 10 {
            hh = "0" + hh
        }

        let tmpTimeString: String = hh + ":" + mm
        
        return tmpTimeString
    }
    
    func getNickNameWithUsername(username : String) -> String {
        let entity = EMUserProfileManager.sharedInstance.getUserProfileByUsername(username: username)
        if entity?.nickname != nil && (entity?.nickname?.count)! > 0 {
            return (entity?.nickname)!
        }
        return username
    }
    
}

extension String {
    //根据开始位置和长度截取字符串
    func subString(start:Int, length:Int = -1) -> String {
        var len = length
        if len == -1 {
            len = self.count - start
        }
        if start < 0 {
            return self
        }
        //注意：不能将self.characters.count改为str0 = self as NSString然后取 str0.length
        //因为NSString汉字和图标算两个字符而self.characters.count中汉字和图标算一个字符，index会溢出
        guard start < self.characters.count else {
            return self
        }
        guard start + length < self.characters.count else {
            return self
        }
        let st = self.index(startIndex, offsetBy:start)
        let en = self.index(st, offsetBy:len)
        return String(self[st ..< en])
    }
}

extension EventsViewController:PGDatePickerDelegate{
    
    func datePicker(_ datePicker: PGDatePicker!, didSelectDate dateComponents: DateComponents!) {
        
        guard let dateComponents = dateComponents,
            let year = dateComponents.year,
            let month = dateComponents.month,
            let day = dateComponents.day else{
                
                return;
        }
        let monthStr = String(format: "%02d", month)
        let dayStr = String(format: "%02d", day)

        let str =  "\(String(describing: year))"  + "-" + monthStr  + "-" + dayStr
        
        showDateStr = getWeekDay(dayStr: str)
        btnSeleteDate.setTitle(showDateStr, for: UIControlState.normal)
        
        getEventsFromBackend(calendarTypeNumber: calendarTypeNumber,dateString: str)
    }
}

extension EventsViewController:UIPickerViewDelegate,UIPickerViewDataSource{
    
    //设置选择框的列数为1列
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    //设置选择框的行数
    func pickerView(_ pickerView: UIPickerView,
                    numberOfRowsInComponent component: Int) -> Int {
        if matchOrFree == 0 {
            return slotsArrMatch.count
        } else {
            return slotsArrFree.count
        }
    }
    
    //设置选择框各选项的内容
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        //赋值
        var tmpStr = ""
        if matchOrFree == 0 {
            if slotsArrMatch.count > 0 {
                tmpStr = slotsArrMatch[row].estartTime + "   " + EnStatic.getWord(keyWord: "to") + "  " + slotsArrMatch[row].eendTime
            }
        } else {
            if slotsArrFree.count > 0 {
                tmpStr = slotsArrFree[row].estartTime + "   " + EnStatic.getWord(keyWord: "to") + "  " + slotsArrFree[row].eendTime
            }
        }
        return tmpStr
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        //选中所执行的方法
        if matchOrFree == 0 {
            selectedSlotMatch = slotsArrMatch[row]
        } else {
            selectedSlotFree = slotsArrFree[row]
        }
    }
    
}
